<template>
  <div class="app-container">
    <el-card class="operate-container" shadow="never" style="margin-bottom: 20px">
      <i class="el-icon-info" />
      <span>考卷信息</span>
      <el-tag v-if="paperInfo.type===0" size="small" type="primary" effect="plain">考试答题</el-tag>
      <el-tag v-else size="small" type="success" effect="plain">调研答题</el-tag>
      <el-button size="mini" class="btn-add" type="success" :disabled="paperInfo.status===1" @click="handleRelease()">发布</el-button>
      <el-button :disabled="paperInfo.status===1" size="mini" class="btn-add" type="primary" @click="handlePaperInfo()">编辑</el-button>
      <el-button size="mini" class="btn-add" @click="goBack()"><i class="el-icon-arrow-left" />返回</el-button>
      <el-form ref="dataForm" :model="paperInfo" label-width="120px" style="margin-top: 15px" size="mini">
        <el-form-item label="考卷标题">
          <span style="width: 450px">{{ paperInfo.title }}</span>
          <el-tag v-if="paperInfo.status===0" size="mini" type="info">未发布</el-tag>
          <el-tag v-else size="mini" type="success">已发布</el-tag>
        </el-form-item>
        <el-form-item v-show="paperInfo.type===0" label="题目总分">
          <span>{{ totalScore }}</span>
        </el-form-item>
        <el-form-item label="起止时间">
          <span>{{ paperInfo.startTime }} 至 {{ paperInfo.endTime }}</span>
          <el-tag v-if="isLaterThanNow(paperInfo.startTime)" size="mini" type="info">未开始</el-tag>
          <el-tag v-else-if="!isLaterThanNow(paperInfo.endTime)" size="mini" type="info">已截止</el-tag>
          <el-tag v-else size="mini" type="success">进行中</el-tag>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="operate-container" shadow="never" style="margin-bottom: 20px">
      <i class="el-icon-tickets" />
      <span>题目信息</span>
      <div class="filter-container" style="margin-top: 15px">
        <el-input v-model="listQuery.content" size="mini" placeholder="题干内容" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-select v-model="listQuery.type" size="mini" placeholder="题型" clearable style="width: 120px;" class="filter-item">
          <el-option v-for="item in typeList" :key="item.key" :label="item.value" :value="item.key" />
        </el-select>
        <el-button v-waves size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          筛选
        </el-button>
        <el-button v-waves :disabled="paperInfo.status===1" size="mini" class="filter-item" type="success" icon="el-icon-edit" @click="handleCreate">
          新增
        </el-button>
        <el-button v-waves :disabled="paperInfo.status===1" size="mini" class="filter-item" icon="el-icon-s-operation" @click="handleQuestionOrder">
          排序
        </el-button>
      </div>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        max-height="690"
        highlight-current-row
        style="width: 100%;"
        :row-style="{height:'32px'}"
        tooltip-effect="light"
      >
        <el-table-column label="序号" type="index" align="center" width="100" />
        <el-table-column label="编号" align="center" width="100px">
          <template slot-scope="{row}">
            <span>{{ row.questionId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="题干信息" align="center" min-width="250px" show-overflow-tooltip>
          <template slot-scope="{row}">
            <span>{{ row.content }}</span>
          </template>
        </el-table-column>
        <el-table-column label="题目详情" align="center" width="200px">
          <template slot-scope="{row}">
            <el-button size="mini" plain @click="showQuestionDetail(row.questionId)">
              查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="题型" align="center" width="150px">
          <template slot-scope="{row}">
            <el-tag size="mini" type="primary" effect="plain">{{ typeMap[row.type] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="分值" align="center" width="150px">
          <template slot-scope="{row}">
            <span>{{ row.score }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280px" class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">
            <el-button type="primary" size="mini" plain icon="el-icon-document-copy" @click="showQuestionStatistic(row.questionId)">
              回答情况
            </el-button>
            <el-button type="danger" size="mini" :disabled="paperInfo.status===1" @click="handleDelete(row.questionId)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-card>

    <el-dialog title="编辑考卷基本信息" :visible.sync="dialogPaperInfoVisible" width="800px" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="paperEditForm" :rules="paperInfoRules" :model="tempPaperInfo" label-width="100px" style="width: 100%" size="small">
        <el-form-item label="id" prop="paperId" hidden>
          <el-input v-model="tempPaperInfo.paperId" style="width: 90%" />
        </el-form-item>
        <el-form-item label="考卷标题" prop="title">
          <el-input v-model="tempPaperInfo.title" style="width: 90%" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="tempPaperInfo.startTime" type="datetime" placeholder="选择考试开始时间" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" />
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker v-model="tempPaperInfo.endTime" type="datetime" placeholder="选择考试开始时间" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm" />
        </el-form-item>
        <el-form-item label="奖品规则" prop="rules" style="width: 90%">
          <tinymce v-if="dialogPaperInfoVisible" v-model="tempPaperInfo.rules" :height="200" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPaperInfoVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="editPaperInfo">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="重新排序题目" :visible.sync="dialogQuestionOrderVisible" width="800px" :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="components-container board">
        <Kanban :key="1" :list="questionOrderList" group="group" class="kanban order" header-text="请拖拽以调整题目顺序" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogQuestionOrderVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateQuestionOrder">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看题目信息" :visible.sync="dialogQuestionDetailVisible" width="700px">
      <el-form :model="questionInfo" :inline="true" label-width="100px" style="width: 90%" size="small">
        <el-form-item label="编号：" style="width: 25%">
          <span style="width: 90%">{{ questionInfo.questionId }}</span>
        </el-form-item>
        <el-form-item v-if="paperInfo.type===0" label="分值：" style="width: 25%">
          <span style="width: 90%">{{ questionInfo.score }}分</span>
        </el-form-item>
        <el-form-item label="题型：" style="width: 40%">
          <el-tag size="mini" type="primary" effect="plain">{{ typeMap[questionInfo.type] }}</el-tag>
          <el-tag v-if="questionInfo.isSurvey===1" size="mini" type="success" effect="plain">无标准答案</el-tag>
        </el-form-item>
        <el-form-item label="题干：" style="width: 100%">
          <span style="width: 90%">{{ questionInfo.content }}</span>
        </el-form-item>
        <el-form-item v-if="questionInfo.type===1 || questionInfo.type===2" label="选项：" style="width: 100%">
          <span v-for="item in questionInfo.questionChooseList">
            {{ item.sign }}. {{ item.content }}
            <br>
          </span>
        </el-form-item>
        <el-form-item v-if="questionInfo.type===3" label="选项：" style="width: 100%">
          <span>1. 正确<br></span>
          <span>2. 错误<br></span>
        </el-form-item>
        <el-form-item v-if="questionInfo.isSurvey===0" label="标准答案：" style="width: 100%">
          <span v-if="questionInfo.type===1 || questionInfo.type===2">
            <span v-for="item in detailAnswerList">{{ questionChooseMap[item] }}</span>
          </span>
          <span v-if="questionInfo.type===3">
            <span v-if="questionInfo.standardAnswer==='T'">正确</span>
            <span v-if="questionInfo.standardAnswer==='F'">错误</span>
          </span>
        </el-form-item>
        <el-form-item label="答案解析：" style="width: 100%">
          <span>{{ questionInfo.standardExplain }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogQuestionDetailVisible = false">
          关闭
        </el-button>
      </div>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogQuestionCreateVisible" width="800px" top="70px" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="dataForm" :model="tempCreateQuestion" label-width="100px" style="width: 100%">
        <el-form-item label="题干" prop="content">
          <el-input v-model="tempCreateQuestion.content" type="textarea" style="width: 90%" />
        </el-form-item>
        <el-form-item v-if="paperInfo.type===0" label="分值" prop="score">
          <el-input-number v-model="tempCreateQuestion.score" size="small" :min="1" :step="1" step-strictly style="text-align: center" />
        </el-form-item>
        <el-form-item label="题型" prop="type">
          <el-radio-group v-model="tempCreateQuestion.type" @change="handleTypeChange">
            <el-radio :label="1">单选题</el-radio>
            <el-radio :label="2">多选题</el-radio>
            <el-radio :label="3">判断题</el-radio>
            <el-radio v-if="paperInfo.type!==0" :label="4">简答题</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="tempCreateQuestion.type===1 || tempCreateQuestion.type===2" label="选项">
          <span v-for="(choice, idx) in tempCreateQuestion.chooseList">
            <span style="display:inline-block; width:20px">{{ choice.sign }}.</span>
            <el-input :key="choice.sign" v-model="choice.content" size="mini" style="width: 65%" />
            <el-button size="mini" type="danger" circle icon="el-icon-delete" plain style="margin-left: 15px" @click="doDeleteChoice(idx)" />
            <el-button v-if="tempCreateQuestion.isSurvey===0 && choice.isAnswer===0" size="mini" type="success" plain round icon="el-icon-check" style="margin-left: 10px" @click="doSetAnswer(idx)">设为答案</el-button>
            <el-button v-else-if="tempCreateQuestion.isSurvey===0 && choice.isAnswer===1" size="mini" type="info" plain round icon="el-icon-close" style="margin-left: 10px" @click="doCancelAnswer(idx)">取消答案</el-button>
            <br>
          </span>
          <el-button size="mini" icon="el-icon-plus" round plain @click="doAddChoice">新增选项</el-button>
        </el-form-item>
        <el-form-item v-if="tempCreateQuestion.type===3" label="选项">
          <span v-for="(judge, idx) in tempCreateQuestion.judgeList">
            <el-tag :key="judge.sign" effect="plain" type="info" style="width: 30%">{{ judge.content }}</el-tag>
            <el-button v-if="tempCreateQuestion.isSurvey===0 && judge.isAnswer===0" size="mini" type="success" plain round icon="el-icon-check" style="margin-left: 10px" @click="doSetAnswer(idx)">设为答案</el-button>
            <el-button v-else-if="tempCreateQuestion.isSurvey===0 && judge.isAnswer===1" size="mini" type="info" plain round icon="el-icon-close" style="margin-left: 10px" @click="doCancelAnswer(idx)">取消答案</el-button>
            <br>
          </span>
        </el-form-item>
        <el-form-item v-if="tempCreateQuestion.type!==4" label="标准答案" prop="isSurvey">
          <el-switch v-model="tempCreateQuestion.isSurvey" :disabled="paperInfo.type===0" :active-value="0" :inactive-value="1" active-color="#13ce66" />
          <div v-if="tempCreateQuestion.isSurvey===0">
            <span v-if="tempCreateQuestion.type===1 || tempCreateQuestion.type===2">
              <span v-for="choice in tempCreateQuestion.chooseList">
                <el-tag v-if="choice.isAnswer===1" size="mini" type="success" effect="plain">{{ choice.sign }}</el-tag>
              </span>
            </span>
            <span v-if="tempCreateQuestion.type===3">
              <span v-for="judge in tempCreateQuestion.judgeList">
                <el-tag v-if="judge.isAnswer===1" size="mini" type="success" effect="plain">{{ judge.content }}</el-tag>
              </span>
            </span>
          </div>
        </el-form-item>
        <el-form-item label="参考解析" prop="standardExplain">
          <el-input v-model="tempCreateQuestion.standardExplain" type="textarea" size="mini" style="width: 90%" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogQuestionCreateVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="doSubmitQuestion">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看回答情况" :visible.sync="dialogQuestionStatisticVisible" width="1000px" top="50px">
      <el-form v-if="dialogQuestionStatisticVisible" :model="questionStatisticInfo" :inline="true" label-width="100px" style="width: 90%; margin-left: auto; margin-right: auto" size="small">
        <el-form-item label="题目编号：" style="width: 25%">
          <span style="width: 90%">{{ questionStatisticInfo.examQuestion.questionId }}</span>
        </el-form-item>
        <el-form-item v-if="questionStatisticInfo.examQuestion.type===0" label="分值：" style="width: 25%">
          <span style="width: 90%">{{ questionStatisticInfo.examQuestion.score }}分</span>
        </el-form-item>
        <el-form-item label="题型：" style="width: 40%">
          <el-tag size="mini" type="primary" effect="plain">{{ typeMap[questionStatisticInfo.examQuestion.type] }}</el-tag>
          <el-tag v-if="questionStatisticInfo.examQuestion.isSurvey===1" size="mini" type="success" effect="plain">无标准答案</el-tag>
        </el-form-item>
        <el-form-item label="题干：" style="width: 100%">
          <span style="width: 90%">{{ questionStatisticInfo.examQuestion.content }}</span>
        </el-form-item>
        <el-form-item v-if="questionStatisticInfo.examQuestion.type===1 || questionStatisticInfo.examQuestion.type===2" label="选项：" style="width: 100%">
          <span v-for="item in questionStatisticInfo.chooseList">
            {{ item.sign }}. {{ item.content }}
            <el-tag size="mini" type="warning" effect="dark">{{ item.answerNum }}人选择</el-tag>
            <br>
          </span>
        </el-form-item>
        <el-form-item v-if="questionStatisticInfo.examQuestion.type===3" label="选项：" style="width: 100%">
          <span v-for="(item, index) in questionStatisticInfo.chooseList">
            {{ index+1 }}. {{ item.content }}
            <el-tag size="mini" type="warning" effect="dark">{{ item.answerNum }}人选择</el-tag>
            <br>
          </span>
        </el-form-item>
        <el-form-item v-if="questionStatisticInfo.examQuestion.isSurvey===0" label="标准答案：" style="width: 100%">
          <span v-if="questionStatisticInfo.examQuestion.type===1 || questionStatisticInfo.examQuestion.type===2">
            <span v-for="item in detailAnswerList">{{ questionChooseMap[item] }}</span>
          </span>
          <span v-if="questionStatisticInfo.examQuestion.type===3">
            <span v-if="questionStatisticInfo.examQuestion.standardAnswer==='T'">正确</span>
            <span v-if="questionStatisticInfo.examQuestion.standardAnswer==='F'">错误</span>
          </span>
        </el-form-item>
        <el-form-item label="题目解析：" style="width: 100%">
          <span>{{ questionStatisticInfo.examQuestion.standardExplain }}</span>
        </el-form-item>
        <el-form-item label="回答人数：" style="width: 100%">
          <span>{{ questionStatisticInfo.totalAnswerNum }}</span>
        </el-form-item>
        <el-form-item v-if="questionStatisticInfo.examQuestion.isSurvey===0" label="正确率：" style="width: 100%">
          <span style="width: 90%">{{ Math.round((questionStatisticInfo.correctAnswerNum / questionStatisticInfo.totalAnswerNum)*100) }}%</span>
        </el-form-item>
        <el-card shadow="never" v-if="questionStatisticInfo.examQuestion.type===4">
          <div slot="header">
            <span>简答题回答详情</span>
            <el-button style="float: right" size="mini" type="primary" icon="el-icon-download" @click="handleExportQuestionExplain(questionStatisticInfo.examQuestion.questionId)">导出</el-button>
          </div>
          <el-table
            :key="questionStatisticInfo.examQuestion.questionId"
            v-loading="answerListLoading"
            :data="answerList"
            border
            fit
            max-height="500"
            highlight-current-row
            style="width: 100%;"
            :row-style="{height:'30px'}"
            tooltip-effect="light"
          >
            <el-table-column label="用户编号" align="center" width="100px">
              <template slot-scope="{row}">
                <span>{{ row.userId }}</span>
              </template>
            </el-table-column>
            <el-table-column label="回答内容" align="center" min-width="250px" show-overflow-tooltip>
              <template slot-scope="{row}">
                <span>{{ row.userAnswer }}</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="answerTotal>0" :total="answerTotal" :page-num.sync="answerListQuery.pageNum" :page-size.sync="answerListQuery.pageSize" @pagination="showUserAnswerList(questionStatisticInfo.examQuestion.questionId)" />
        </el-card>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {
  showQuestionList,
  getPaperInfo,
  editPaperInfo,
  sumPaperScore,
  orderQuestions,
  getQuestionInfo,
  releasePaper,
  addPaperQuestion,
  deleteQuestion,
  getQuestionAnswerStatistics,
  showUserAnswerList,
  exportQuestionExplain
} from '@/api/exam'
import { isLaterThanNow } from '@/utils/date'
import waves from '@/directive/waves'
import Tinymce from '@/components/Tinymce'
import Kanban from '@/components/Kanban'
import Pagination from '@/components/Pagination'

const defaultTempCreateQuestion = {
  chooseList: [],
  judgeList: [],
  isSurvey: 0
}
const defaultJudgeList = [
  { sign: 'T', content: '正确', isAnswer: 0 },
  { sign: 'F', content: '错误', isAnswer: 0 }
]

export default {
  name: 'Paper',
  components: { Tinymce, Kanban, Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: [],
      answerList: [],
      total: 0,
      answerTotal: 0,
      listLoading: true,
      answerListLoading: true,
      dialogLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10000,
        sortProp: '',
        sortOrder: '',
        title: '',
        type: '',
        status: ''
      },
      answerListQuery: {
        pageNum: 1,
        pageSize: 20,
        questionId: ''
      },
      dialogStatus: '',
      textMap: {
        update: '编辑题目',
        create: '新增题目'
      },
      totalScore: '',
      paperInfo: {},
      questionInfo: {},
      questionStatisticInfo: {},
      detailAnswerList: [],
      questionChooseMap: {},
      tempPaperInfo: {},
      questionOrderList: [],
      tempCreateQuestion: Object.assign({}, defaultTempCreateQuestion),
      paperInfoRules: {
        title: [{ required: true, message: '请填写试卷标题', trigger: 'blur' }],
        rules: [{ required: true, message: '请编辑奖品规则', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }]
      },
      dialogPaperInfoVisible: false,
      dialogQuestionOrderVisible: false,
      dialogQuestionDetailVisible: false,
      dialogQuestionCreateVisible: false,
      dialogQuestionStatisticVisible: false,
      typeList: [
        { key: 1, value: '单选题' },
        { key: 2, value: '多选题' },
        { key: 3, value: '判断题' },
        { key: 4, value: '简答题' }
      ],
      typeMap: {
        1: '单选题',
        2: '多选题',
        3: '判断题',
        4: '简答题'
      }
    }
  },
  created() {
    this.getPaperInfo()
    this.showQuestionList()
  },
  methods: {
    sumPaperScore() {
      if (this.paperInfo.type === 0) {
        sumPaperScore(this.$route.params.paperId).then(response => {
          this.totalScore = response.data
        })
      }
    },
    getPaperInfo() {
      getPaperInfo(this.$route.params.paperId).then(response => {
        this.paperInfo = response.data
        this.sumPaperScore()
      })
    },
    resetPaperInfoDialog() {
      this.tempPaperInfo = Object.assign({}, this.paperInfo)
    },
    handlePaperInfo() {
      this.resetPaperInfoDialog()
      this.dialogPaperInfoVisible = true
    },
    editPaperInfo() {
      this.$refs['paperEditForm'].validate((valid) => {
        if (valid) {
          editPaperInfo(this.tempPaperInfo).then(() => {
            this.getPaperInfo()
            this.dialogPaperInfoVisible = false
            this.$notify({
              title: 'Success',
              message: '编辑考卷基本信息成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleQuestionOrder() {
      this.questionOrderList = []
      this.list.forEach(q => {
        this.questionOrderList.push({
          id: q.questionId,
          name: q.content
        })
      })
      this.dialogQuestionOrderVisible = true
    },
    updateQuestionOrder() {
      const resultList = []
      let i = 0
      this.questionOrderList.forEach(q => {
        resultList.push({
          questionId: q.id,
          questionOrder: ++i
        })
      })
      orderQuestions({
        paperId: this.$route.params.paperId,
        list: resultList
      }).then(() => {
        this.getPaperInfo()
        this.showQuestionList()
        this.dialogQuestionOrderVisible = false
        this.$notify({
          title: 'Success',
          message: '重新排序成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    showQuestionList() {
      this.listLoading = true
      this.listQuery.paperId = this.$route.params.paperId
      showQuestionList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.showQuestionList()
    },
    sortChange(data) {
      const { prop, order } = data
      this.listQuery.sortProp = prop
      if (order === 'ascending') {
        this.listQuery.sortOrder = '1'
      } else {
        this.listQuery.sortOrder = '-1'
      }
      this.handleFilter()
    },
    showQuestionDetail(questionId) {
      getQuestionInfo(questionId).then(response => {
        this.questionInfo = response.data
        // 生成选项map
        if (this.questionInfo.type === 1 || this.questionInfo.type === 2) {
          this.questionChooseMap = {}
          this.questionInfo.questionChooseList.forEach(c => {
            this.questionChooseMap[c.chooseId] = c.sign
          })
          const answerStr = '[' + this.questionInfo.standardAnswer + ']'
          this.detailAnswerList = JSON.parse(answerStr)
        }
        this.dialogQuestionDetailVisible = true
      })
    },
    showQuestionStatistic(questionId) {
      getQuestionAnswerStatistics(questionId).then(response => {
        this.questionStatisticInfo = response.data
        // 生成选项map
        if (this.questionStatisticInfo.examQuestion.type === 1 || this.questionStatisticInfo.examQuestion.type === 2) {
          this.questionChooseMap = {}
          this.questionStatisticInfo.chooseList.forEach(c => {
            this.questionChooseMap[c.chooseId] = c.sign
          })
          const answerStr = '[' + this.questionStatisticInfo.examQuestion.standardAnswer + ']'
          this.detailAnswerList = JSON.parse(answerStr)
        }
        this.dialogQuestionStatisticVisible = true
        if (this.questionStatisticInfo.examQuestion.type === 4) {
          this.initUserAnswerList(questionId)
        }
      })
    },
    handleRelease() {
      this.$confirm('此操作将发布该考卷，发布后将无法再对其进行修改，是否继续?', '提示', {
        confirmButtonText: '确认发布',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        releasePaper(this.$route.params.paperId).then(() => {
          this.$router.go(0)
          this.$notify({
            title: 'Success',
            message: '发布成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    resetCreateDialog() {
      this.tempCreateQuestion = Object.assign({}, defaultTempCreateQuestion)
      this.tempCreateQuestion.chooseList = [
        { sign: 'A', content: null, isAnswer: 0 },
        { sign: 'B', content: null, isAnswer: 0 },
        { sign: 'C', content: null, isAnswer: 0 },
        { sign: 'D', content: null, isAnswer: 0 }
      ]
      this.tempCreateQuestion.judgeList = Object.assign([], defaultJudgeList)
    },
    handleCreate() {
      this.resetCreateDialog()
      this.dialogStatus = 'create'
      this.dialogQuestionCreateVisible = true
    },
    doDeleteChoice(idx) {
      // 删除
      this.tempCreateQuestion.chooseList.splice(idx, 1)
      // 重新调整sign
      let i = 0
      this.tempCreateQuestion.chooseList.forEach(choice => {
        choice.sign = String.fromCharCode('A'.charCodeAt(0) + i)
        i++
      })
    },
    doAddChoice() {
      this.tempCreateQuestion.chooseList.push({
        sign: String.fromCharCode('A'.charCodeAt(0) + this.tempCreateQuestion.chooseList.length),
        content: '',
        isAnswer: 0
      })
    },
    doSetAnswer(idx) {
      // 单选判断题只能选一个 先行判断
      let list = []
      switch (this.tempCreateQuestion.type) {
        case 1: // 单选
          list = this.tempCreateQuestion.chooseList
          if (this.checkAnswerExist(list)) { // 已存在答案
            this.$message({ message: '单选题不可选择多个答案', type: 'warning' })
            return
          }
          break
        case 2: // 多选
          list = this.tempCreateQuestion.chooseList
          break
        case 3: // 判断
          list = this.tempCreateQuestion.judgeList
          if (this.checkAnswerExist(list)) { // 已存在答案
            this.$message({ message: '判断题不可选择多个答案', type: 'warning' })
            return
          }
          break
        default:
          return
      }
      // 设置答案
      if (list[idx]) list[idx].isAnswer = 1
    },
    checkAnswerExist(list) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].isAnswer === 1) {
          return true
        }
      }
      return false
    },
    doCancelAnswer(idx) {
      let list = []
      switch (this.tempCreateQuestion.type) {
        case 1: // 单选
          list = this.tempCreateQuestion.chooseList
          break
        case 2: // 多选
          list = this.tempCreateQuestion.chooseList
          break
        case 3: // 判断
          list = this.tempCreateQuestion.judgeList
          break
        default:
          return
      }
      // 取消答案
      if (list[idx]) list[idx].isAnswer = 0
    },
    handleTypeChange(label) { // 切换题目类型时
      // 若为简答题 自动将isSurvey设为1
      if (label === 4) {
        this.tempCreateQuestion.isSurvey = 1
      }
      this.emptyAnswers()
    },
    emptyAnswers() { // 切换类型时清空答案
      this.tempCreateQuestion.chooseList.forEach(choice => {
        choice.isAnswer = 0
      })
      this.tempCreateQuestion.judgeList.forEach(choice => {
        choice.isAnswer = 0
      })
    },
    doSubmitQuestion() {
      const questionInfo = Object.assign({}, this.tempCreateQuestion)
      // 数据检查：通用数据检查、分值检查、选项及答案检查
      // 通用数据检查
      if (!questionInfo.content) {
        this.$message({ message: '请填写题干信息', type: 'error' })
        return
      }
      if (!questionInfo.type) {
        this.$message({ message: '请选择题型', type: 'error' })
        return
      }
      // 考试答题/调研答题
      if (this.paperInfo.type === 0) {
        if (!questionInfo.score) {
          this.$message({ message: '请设置题目分值', type: 'error' })
          return
        }
      }
      // 选项及答案检查：
      // 1.选项数量及内容完整性
      if (questionInfo.type === 1 || questionInfo.type === 2) { // 选择题
        if (questionInfo.chooseList.length <= 1) {
          this.$message({ message: '请添加至少两个选项', type: 'error' })
          return
        }
        for (let i = 0; i < questionInfo.chooseList.length; i++) {
          if (!questionInfo.chooseList[i].content) {
            this.$message({ message: '选项内容不能为空', type: 'error' })
            return
          }
        }
      }
      // 2.标准答案是否合理
      if (questionInfo.isSurvey === 0) {
        let answerCount = 0
        switch (questionInfo.type) {
          case 1: // 单选 只有一个答案
            questionInfo.chooseList.forEach(item => {
              if (item.isAnswer === 1) answerCount++
            })
            if (answerCount > 1) {
              this.$message({ message: '单选题只能设置一个标准答案', type: 'error' })
              return
            }
            break
          case 2: // 多选 至少一个答案
            questionInfo.chooseList.forEach(item => {
              if (item.isAnswer === 1) answerCount++
            })
            break
          case 3: // 判断 只有一个答案
            questionInfo.judgeList.forEach(item => {
              if (item.isAnswer === 1) answerCount++
            })
            if (answerCount > 1) {
              this.$message({ message: '判断题只能设置一个标准答案', type: 'error' })
              return
            }
            break
          default:
            break
        }
        if (answerCount < 1) {
          this.$message({ message: '请设置标准答案', type: 'error' })
          return
        }
      }
      // 设置paperId
      questionInfo.paperId = this.paperInfo.paperId
      // 提交数据
      addPaperQuestion(questionInfo).then(() => {
        this.$notify({
          title: 'Success',
          message: '添加题目成功！',
          type: 'success',
          duration: 2000
        })
        this.showQuestionList()
        this.dialogQuestionCreateVisible = false
      })
    },
    handleDelete(questionId) {
      this.$confirm('此操作将删除该题目，且不可逆，是否继续?', '提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteQuestion(questionId).then(() => {
          this.showQuestionList()
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      })
    },
    initUserAnswerList(questionId) {
      this.answerListQuery = {
        pageNum: 1,
        pageSize: 20,
        questionId: ''
      }
      this.showUserAnswerList(questionId)
    },
    showUserAnswerList(questionId) {
      this.answerListLoading = true
      this.answerListQuery.questionId = questionId
      showUserAnswerList(this.answerListQuery).then(response => {
        this.answerList = response.data.list
        this.answerTotal = response.data.total
        this.answerListLoading = false
      })
    },
    handleExportQuestionExplain(questionId) {
      const loading = this.$loading({
        lock: true,
        text: '正在导出中，请耐心等待',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      exportQuestionExplain(questionId).then((response) => {
        this.$notify({
          title: '简答题用户回答列表导出成功',
          dangerouslyUseHTMLString: true,
          message: '<p>已生成简答题用户回答列表，请下载：</p>' +
            '<a target="_blank" href="' + response.data + '">' +
            '<strong style="text-decoration: underline">点击下载</strong>' +
            '</a>',
          type: 'success',
          duration: 0
        })
        loading.close()
      })
    },
    isLaterThanNow(date) {
      return isLaterThanNow(date)
    },
    goBack() {
      this.$router.go(-1)
    }
  }
}
</script>

<style lang="scss" scoped>
  .issue-content {
    font-size: 18px;
    line-height: 31px;
  }
  .operate-container .btn-add {
    float: right;
    margin-left: 10px;
  }
</style>
